import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class update {
    public static void main(String[] args) throws SQLException {
        //让用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改的id: ");
        int id = scanner.nextInt();
        System.out.println("请输入要修改的姓名: ");
        String name = scanner.next();
        System.out.println("请输入修改后的id: ");
        int id2 = scanner.nextInt();
        System.out.println("请输入修改后的姓名: ");
        String name2 = scanner.next();
        //1.创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/mdx?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("021642");
        //和数据库服务器建立连接
        Connection connection =dataSource.getConnection();
        System.out.println(connection);
        //3.构造SQL语句
        String sql = "update student set id = ?,name = ? where id = ? and name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id2);
        statement.setString(2,name2);
        statement.setInt(3,id);
        statement.setString(4,name);
        //4.把SQL发送到服务器上执行
        int n = statement.executeUpdate();
        System.out.println(n);
        //5.释放资源
        statement.close();
        connection.close();
    }
}
